﻿using Microsoft.OpenApi.Models;

namespace XKJ.OAWeb.Api.Config
{
    public static class SwaggerConfig
    {
        public static void Swagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(c => {
                //获取应用程序的所在目录
                var basePath = AppContext.BaseDirectory;
                //或者用下面的方式也能获取
                var basePath2 = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                //拼接XML文件所 在路径
                var xmlPath = System.IO.Path.Combine(basePath, "XKJ.OAWeb.Api.xml"); 
                //让Swagger显示方法、类的XML注释信息
                c.IncludeXmlComments(xmlPath, true);
                //设置Swagger文档参数
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "XKJ.OAWeb.Api",
                    Version = "v1",
                    //描述信息
                    Description = "Asp.Net Core6 WebApi模拟开发",
                    //开发者信息
                    Contact = new OpenApiContact()
                    {
                        Name = "徐康佳",
                        Email = "99825949@qq.com",
                    }
                });
                //开启Authorize权限按钮
                c.AddSecurityDefinition("JWTBearer", new OpenApiSecurityScheme()
                {
                    Description = "这是方式一(直接在输入框中输入认证信息，不需要在开头添加Bearer) ",
                    Name = "Authorization", //jwt默认的参数名称
                    In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.Http,
                    Scheme = "Bearer"
                });
                //声明一个Scheme，注意下面的Id要和上面AddSecurityDefinition中的参数name一致
                var scheme = new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference()
                    {
                        //这个名字与上面的一样
                        Id = "JWTBearer", 
                        Type = ReferenceType.SecurityScheme
                    }
                };
                //注册全局认证（所有的接口都可以使用认证）
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { scheme, Array.Empty<string>() }
                });
                
            });
        }
    }
}
